import { App, HTMLAttributes, VNode, VNodeTypes } from 'vue'
import { render } from '../_util/props-util'
import { MessageProps } from '../MessageManager/Message'
import { MessageManagerExpose, newInstace } from '../MessageManager'

import Icon from '../icon'
import './style'

type BaseOption = HTMLAttributes & {
  title: VNodeTypes
  description?: VNodeTypes
  content?: VNodeTypes
  cover?: VNodeTypes
  icon?: VNode
  meta: VNodeTypes
  duration?: number
  closable?: boolean
}

export type NotificationOption = Omit<MessageProps, keyof BaseOption> & BaseOption

const prefixCls = 'x-notification'
const instance = newInstace({ prefixCls })

let __key = 0
function getKey() {
  return '__' + __key++
}

const Notification = {
  create: (options: NotificationOption) => {
    const key = options.key ?? getKey()
    const obj = instance.add({
      ...options,
      key,
      duration: options.duration === undefined ? 5000 : options.duration,
      default: () => {
        return (
          <div class={prefixCls}>
            <div v-show={options.cover} class={`${prefixCls}_cover`}>
              {render(options.cover)}
            </div>
            <div class={`${prefixCls}_header`}>
              <div class={`${prefixCls}_title`}>{render(options.title)}</div>
              <div v-show={options.closable} class={`${prefixCls}_close`} onClick={onClose}>
                {<Icon type='cross' />}
              </div>
              <div v-show={options.description} class={`${prefixCls}_description`}>
                {render(options.description)}
              </div>
              <div v-show={options.meta} class={`${prefixCls}_meta`}>
                {render(options.meta)}
              </div>
            </div>
          </div>
        )
      },
      transitionProps: { width: 0, height: 0 }
    } as MessageProps)

    function onClose(e: MouseEvent) {
      e.preventDefault()
      e.stopPropagation()
      obj.close()
    }
    return obj.close
  },
  destroyAll: instance.removeAll,
  // Plugin
  install(app: App) {
    app.config.globalProperties.$notification = Notification
  }
}

export type Notification = typeof Notification

export default Notification
